#include "mysqlutili.h"

// static number
MYSQL MYSQLUTILI::connection;
bool MYSQLUTILI::initIsOkay = false;

MYSQLUTILI::MYSQLUTILI(const char *h,unsigned int p,const char *u,const char *pwd,const char *db_name,const char *unix_socket,unsigned long client_flag){
	if (!initIsOkay){
		mysql_init(&connection);
		bool is_scueed = mysql_real_connect(&connection, h, u, pwd, db_name, p, unix_socket, client_flag);
		if (!is_scueed){
			fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(&connection));
			exit(1);
		}
		mysql_query(&connection, "SET NAMES utf8");
		printf("Connect database successfully! \n");
		initIsOkay = true;
	}
}

MYSQLUTILI::~MYSQLUTILI(){
	mysql_close(&connection);
}

int MYSQLUTILI::executeForUpdate(char* exec_sql){
	// int result = mysql_query(&connection, exec_sql.c_str());    ‘0’ means successful
	if(!mysql_query(&connection, exec_sql)){
		return 1;  // okay
	}
	return -1;  // flooey
}

string MYSQLUTILI::executeForResult(char* exec_sql){
	string result = "";
	// In mysql_query method, the second parameter should be converted to char array. (use c_str [string -> char*])
	int ccount = mysql_query(&connection, exec_sql);
	// execute successfully!
	if(ccount == 0){
		results_set = mysql_store_result(&connection);
		int count = mysql_num_rows(results_set);
		// The count is greater than zero if any result.
		if ( count > 0){
			// count(columns)
			int colNum = mysql_num_fields(results_set);
			// columns
			MYSQL_FIELD* field = mysql_fetch_fields(results_set);
			for (int i = 0; i < colNum; i++){
				string colName = field[i].name;
				if (i == (colNum-1) ){
					result += colName + '\n';
				}else{
					result += colName + ',';
				}
			}
			// result of row
			while ((temp_row = mysql_fetch_row(results_set)) != NULL){
				for (int i = 0; i< colNum; i++){
					string tmp = (temp_row[i] != NULL ? temp_row[i] : "NULL");
					if (i == (colNum-1) ){
						result += tmp + '\n';
					}else{
						result += tmp + ',';
					}
				}
			}
			mysql_free_result(results_set);
		}
	}
	return result;
}
